<?php
namespace app\controller;

use app\BaseController;
use think\facade\Db;
use think\Request;
use think\captcha\facade\Captcha;
use think\cache\driver\Redis;
use think\facade\Cache;
/**
* 
*/
class Login extends BaseController
{
	
	protected $userInfo;
	protected $request;
	public function __construct(Request $request){
        // $token = Request::instance()->header('token');
        $this->request = $request;
	}
	//登录
	public function login(){
		$redis = new Redis();
		$requests = new Request_type();

		$redis->handler()->select(10);

		$data = $this->request->param();
		$userInfo = Db::table("t_user")->where("user_name",$data['username'])->find();

		if(!$userInfo){
			return json_encode(array("code"=>"109","msg"=>"該帳戶不存在"));
		}
		if($userInfo['status'] != 0){
			return json_encode(array("code"=>"111","msg"=>"該帳戶禁止登入"));
		}
		if(md5(md5($data['password'].$userInfo['salt'])) != $userInfo['password']){
			return json_encode(array("code"=>"110","msg"=>"登入密碼不正確"));
		}
		$token = md5($userInfo['id'].$userInfo['invite_code'].substr(time(),-6));
		$u['login_times'] = $userInfo['login_times'] + 1;
		$u['last_login_ip'] = $requests->get_client_ip();
		$u['last_login_time'] = date("Y-m-d H:i:s");

		Db::table("t_user")->where("id",$userInfo['id'])->update($u);
		$user_token = Db::table("t_user_token")->where("user_id",$userInfo['id'])->find();
		if($user_token){
		    $redis->delete($user_token['token']);
			Db::table("t_user_token")->where("user_id",$userInfo['id'])->update(['token'=>$token,'expire_time'=>time()+24*2600*3,'last_update_time'=>time()]);
		}else{
			$u_token = array(
				"user_id"=>$userInfo['id'],
				"token"=>$token,
				"expire_time"=>time()+24*2600*3,
				"last_update_time"=>time()
			);
			Db::table("t_user_token")->save($u_token);
		}

		$redis->set($token,$userInfo);

		return json_encode(array("code"=>200,'msg'=>'成功','token'=>$token));
	}
	//退出登录
	public function logout(){
		$redis = new Redis();
		$requests = new Request_type();
		$redis->handler()->select(10);
		$token = $this->request->header('token');
		if($token){
			$redis->delete($token);
		}
		return json_encode(array("code"=>200,'msg'=>'成功'));
	}
}